package com.smasher.backup.dialog.select.delegate

import android.util.Log
import android.util.SparseIntArray
import android.view.View
import androidx.core.util.isEmpty
import androidx.core.util.remove
import com.smasher.backup.dialog.select.SelectMode
import com.smasher.backup.dialog.select.listener.OnInternSelectListener

open class SelectDelegate(
    var mode: SelectMode
) : OnInternSelectListener {

    val selectedArray = SparseIntArray()

    fun isSelected(position: Int): Boolean {
        if (selectedArray.isEmpty()) {
            return false
        }
        return selectedArray.indexOfKey(position) >= 0
    }

    open fun notifyAdapterItemChanged(sparseIntArray: SparseIntArray) {

    }

    override fun onSelect(index: Int, view: View) {
        Log.d(TAG, "onSelect: ")
        when (mode) {
            SelectMode.SINGLE -> {
                val temp = selectedArray.clone()
                selectedArray.clear()
                selectedArray.put(index, index)
                temp.put(index, index)
                view.post {
                    notifyAdapterItemChanged(temp)
                }
            }

            SelectMode.MULTI -> {
                if (selectedArray.indexOfKey(index) < 0) {
                    selectedArray.put(index, index)
                }
                val temp = SparseIntArray().apply {
                    put(index, index)
                }
                view.post {
                    notifyAdapterItemChanged(temp)
                }
            }
        }
    }

    override fun unSelect(index: Int, view: View) {
        Log.d(TAG, "unSelect: ")
        when (mode) {
            SelectMode.SINGLE -> {
                val temp = SparseIntArray()
                val target = selectedArray.indexOfKey(index)
                if (target >= 0) {
                    selectedArray.remove(target, target)
                }
                temp.put(index, index)
                view.post {
                    notifyAdapterItemChanged(temp)
                }
            }

            SelectMode.MULTI -> {
                val temp = SparseIntArray()
                val target = selectedArray.indexOfKey(index)
                if (target >= 0) {
                    selectedArray.remove(index, index)
                }
                temp.put(index, index)
                view.post {
                    notifyAdapterItemChanged(temp)
                }
            }
        }
    }

    companion object {
        const val TAG = "SelectDelegate"
    }
}